package com.my.zl.common.utils;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author zhouliang
 *
 */
public abstract class JsonUtil {

    /**
     * The Constant LOGGER.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * The object mapper.
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        objectMapper.configure(Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    }

    /**
     * Convert to json.
     *
     * @param object the object
     * @return the string
     */
    public static String convertToJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            LOGGER.error("convert failed", e);
            return "";
        }
    }

    public static <T> T json2Bean(String json, Class<T> T) {
        try {
            T obj = objectMapper.readValue(json, T);
            return obj;
        } catch (Exception e) {
            LOGGER.error("convert failed", e);
            return null;
        }
    }

    public static <T> T json2Bean(String json, JavaType T) {
        try {
            T obj = objectMapper.readValue(json, T);
            return obj;
        } catch (Exception e) {
            LOGGER.error("convert failed", e);
            return null;
        }
    }

    public static <T> List<T> json2List(String json, Class<T> T) {
        JavaType javaType = getCollectionType(ArrayList.class, T);
        List<T> lst;
        try {
            lst = objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            LOGGER.error("convert failed", e);
            return null;
        }
        return lst;
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
}